package com.lxp.eduService.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lxp.eduService.domain.EduSubject;
import com.lxp.eduService.domain.excel.SubjectLevel;
import com.lxp.eduService.domain.vo.subject.OneSubject;
import com.lxp.eduService.domain.vo.subject.TwoSubject;
import com.lxp.eduService.listener.ExcelListener;
import com.lxp.eduService.mapper.EduSubjectMapper;
import com.lxp.eduService.service.EduSubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;


import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

import java.util.Objects;


/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author lxp
 * @since 2021-11-18
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {


    //通过Excel读取xls 添加课程
    @Override
    public void saveSubject(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(), SubjectLevel.class,new ExcelListener(this)).sheet().doRead();
        }catch (Exception e){

        }
    }

    //获取课程目录
    @Override
    public List<OneSubject> getFinalSubject() {

        QueryWrapper<EduSubject> wrapper =new QueryWrapper<>();
        wrapper.eq("parent_id","0");

        //最后返回的list
        List<OneSubject> finalList =new ArrayList<>();
        //获取所有一级目录
        List<EduSubject> firstSubject = (List<EduSubject>) baseMapper.selectList(wrapper);
        //将firstSubject 封装到 finalList
        for (EduSubject eduSubject : firstSubject) {
            OneSubject oneSubject =new OneSubject();
            //将firstSubject的同名属性迁移到oneSubject
            BeanUtils.copyProperties(eduSubject,oneSubject);
            finalList.add(oneSubject);
        }

        wrapper=new QueryWrapper<>();
        //获取所有二级目录
        wrapper.ne("parent_id","0");
        List<EduSubject> secondSubject = (List<EduSubject>) baseMapper.selectList(wrapper);
        //遍历二级目录封装到TwoSubject去 将二级目录TwoSubject存到一级目录OneSubject下
        for (OneSubject oneSubject : finalList) {

            List<TwoSubject> twoSubjects =new ArrayList<>();
            //判断二级目录是输入哪个目录的
            for (EduSubject twoSubject : secondSubject) {
                //id 和 parentId对应
                if (Objects.equals(oneSubject.getId(),twoSubject.getParentId())){
                    TwoSubject subject =new TwoSubject();
                    BeanUtils.copyProperties(twoSubject,subject);
                    twoSubjects.add(subject);
                    continue;
                }
            }
            oneSubject.setChildren(twoSubjects);

        }
        return finalList;
    }
}
